const userList = [{
	user: 'admin',
	pwd: 'admin',
	role: 'admin'
}, {
	user: '张三',
	pwd: '123',
	role: 'user'
}, {
	user: '王五',
	pwd: '12345',
	role: 'user'
}]
let { list } = require('./mock')
const JWT = require('jsonwebtoken')
const bodyParser = require('body-parser')
const keyword = '666666'
module.exports = app => {
	app.use(bodyParser.json())
	// 用户登录接口
	app.post('/api/user/login', (req, res) => {
		const { user, pwd } = req.body;
		const curr = userList.find(v => v.user === user && v.pwd === pwd)

		if (curr) {
			res.send({
				code: 200,
				data: {
					token: JWT.sign({ role: curr.role, user: curr.user }, keyword)
				}
			})
		} else {
			res.send({
				code: 404,
				data: null,
				mess: '账户密码错误， 请重新登录！'
			})
		}
	})

	// 列表请求接口
	app.get('/api/list', (req, res) => {
		res.send({
			code: 200,
			data: list
		})
	})

	// 列表删除接口 (支持多个删除)
	app.post('/api/list/delete', (req, res) => {
		// 要求 传递一个数组 数组包含被删除的key
		const { keys } = req.body
		// 通过filter 过滤需要被删除的key
		list = list.filter(v => !keys.includes(v.key))

		res.send({
			code: 200,
			data: null,
			mess: '删除成功'
		})
	})


	// 列表修改接口
	app.post('/api/list/edit', (req, res) => {
		const { key } = req.body
		const item = list.find(v => v.key === key)
		Object.assign(item, req.body)
		res.send({
			code: 200,
			data: null,
			mess: '修改成功'
		})
	})

	// 获取用户信息
	app.post('/api/user/info', (req, res) => {
		const { token } = req.body
		try {
			const info = JWT.verify(token, keyword)
			res.send({
				code: 200,
				data: info
			})
		} catch {
			res.send({
				code: 401,
				data: '非法token, 返回首页'
			})
		}
	
	})
}